package com.rayboo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.rayboo.model.AdminUser;
import com.rayboo.model.AdminUserDetails;
import com.rayboo.model.AdminUserRole;

/**
 * 
 * AuthUserDetailsService
 * 
 * @author ray
 * @date 2016年9月8日 下午8:10:25
 *
 */
@Service
public class AuthUserDetailsService implements UserDetailsService {

	@Autowired
	private AdminUserService userService;
	@Autowired
	private AdminUserRoleService userRoleService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		AdminUser user;
        try {
            user = userService.findByUsername(username);
        } catch (Exception e) {
            throw new UsernameNotFoundException("user select fail");
        }
        if(user == null){
            throw new UsernameNotFoundException("no user found");
        } else {
            try {
                List<AdminUserRole> roles = userRoleService.findRoleByUser(user);
                return new AdminUserDetails(user, roles);
            } catch (Exception e) {
                throw new UsernameNotFoundException("user role select fail");
            }
        }
	}
	
}